import cv2
import numpy as np


class Contrast(object):
    """
    滑块识别
    """
    def __init__(self, bg, gap):
        self.bg = self.init_img(bg)
        self.gap = self.init_img(gap)

    @staticmethod
    def init_img(img):
        if isinstance(img, str):
            img = cv2.imread(img)
        if isinstance(img, np.ndarray):
            cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            return img
        return False

    @staticmethod
    def img_show(img, win_name='Show'):
        cv2.imshow(win_name, img)
        cv2.waitKey()
        cv2.destroyAllWindows()

    def distance(self, xy='x', show=False):
        bg_gray = self.bg
        gap_gray = self.gap
        if bg_gray is False or gap_gray is False:
            raise
        bg_gray = cv2.Canny(bg_gray, 255, 255)
        gap_gray = cv2.Canny(gap_gray, 255, 255)
        result = cv2.matchTemplate(bg_gray, gap_gray, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        x, y = max_loc[0], max_loc[1]
        if show:
            tp_height, tp_width = gap_gray.shape[:2]
            x, y = max_loc
            _x, _y = x + tp_width, y + tp_height
            bg_img = self.bg
            cv2.rectangle(self.bg, (x, y), (_x, _y), (0, 0, 255), 2)
            self.img_show(bg_img)
        if xy == 'x':
            return x
        elif xy == 'y':
            return y
        else:
            return [x, y]
